package com.sssre.lttcloud.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sssre.lttcloud.auth.entity.AuthUser;
import com.sssre.lttcloud.auth.mapper.UserMapper;
import com.sssre.lttcloud.auth.service.UserService;
import com.sssre.lttcloud.common.result.Result;
import com.sssre.lttcloud.common.result.ResultCode;
import com.sssre.lttcloud.common.utils.JwtUtils;
import com.sssre.lttcloud.common.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtil redisUtil;

    private static final String TOKEN_PREFIX = "token:";
    private static final String USER_PREFIX = "user:";
    private static final long TOKEN_EXPIRE_TIME = 7200; // 2小时
    private static final long REFRESH_TOKEN_EXPIRE_TIME = 604800; // 7天

    @Override
    public Result login(String username, String password) {
        try {
            // 查找用户
            AuthUser user = findByUsername(username);
            if (user == null) {
                return Result.failed(ResultCode.USER_NOT_FOUND);
            }

            // 验证密码
            if (!passwordEncoder.matches(password, user.getPassword())) {
                return Result.failed(ResultCode.PASSWORD_ERROR);
            }

            // 检查用户状态
            if (user.getStatus() != 1) {
                return Result.failed(ResultCode.USER_DISABLED);
            }

            // 生成token
            String token = jwtUtils.generateToken(user.getUsername());
            String refreshToken = jwtUtils.generateToken(user.getUsername());

            // 存储到Redis
            String tokenKey = TOKEN_PREFIX + user.getUsername();
            String userKey = USER_PREFIX + user.getUsername();
            
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            tokenMap.put("refreshToken", refreshToken);
            tokenMap.put("userId", user.getId());
            tokenMap.put("username", user.getUsername());
            
            redisUtil.hmset(tokenKey, tokenMap, TOKEN_EXPIRE_TIME);
            redisUtil.set(userKey, user, TOKEN_EXPIRE_TIME);

            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("refreshToken", refreshToken);
            data.put("user", user);

            return Result.success(data);
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result register(AuthUser user) {
        try {
            // 检查用户名是否已存在
            LambdaQueryWrapper<AuthUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AuthUser::getUsername, user.getUsername());
            
            if (userMapper.selectCount(queryWrapper) > 0) {
                return Result.failed(ResultCode.USERNAME_EXISTS);
            }

            // 检查邮箱是否已存在
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AuthUser::getEmail, user.getEmail());
            
            if (userMapper.selectCount(queryWrapper) > 0) {
                return Result.failed(ResultCode.EMAIL_EXISTS);
            }

            // 加密密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            user.setStatus(1); // 默认启用

            // 保存用户
            int result = userMapper.insert(user);
            if (result > 0) {
                return Result.success(user);
            } else {
                return Result.failed(ResultCode.OPERATION_FAILED);
            }
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result logout(String token) {
        try {
            String username = jwtUtils.getUsernameFromToken(token);
            if (username != null) {
                // 从Redis中删除token
                String tokenKey = TOKEN_PREFIX + username;
                String userKey = USER_PREFIX + username;
                redisUtil.del(tokenKey, userKey);
            }
            return Result.success();
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result refreshToken(String refreshToken) {
        try {
            String username = jwtUtils.getUsernameFromToken(refreshToken);
            if (username == null) {
                return Result.failed(ResultCode.TOKEN_INVALID);
            }

            // 检查用户是否存在
            AuthUser user = findByUsername(username);
            if (user == null) {
                return Result.failed(ResultCode.USER_NOT_FOUND);
            }

            // 生成新的token
            String newToken = jwtUtils.generateToken(username);
            String newRefreshToken = jwtUtils.generateToken(username);

            // 更新Redis中的token
            String tokenKey = TOKEN_PREFIX + username;
            String userKey = USER_PREFIX + username;
            
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("token", newToken);
            tokenMap.put("refreshToken", newRefreshToken);
            tokenMap.put("userId", user.getId());
            tokenMap.put("username", user.getUsername());
            
            redisUtil.hmset(tokenKey, tokenMap, TOKEN_EXPIRE_TIME);
            redisUtil.set(userKey, user, TOKEN_EXPIRE_TIME);

            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", newToken);
            data.put("refreshToken", newRefreshToken);

            return Result.success(data);
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public AuthUser findByUsername(String username) {
        LambdaQueryWrapper<AuthUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuthUser::getUsername, username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean validateToken(String token) {
        try {
            String username = jwtUtils.getUsernameFromToken(token);
            if (username == null) {
                return false;
            }

            // 检查Redis中是否存在token
            String tokenKey = TOKEN_PREFIX + username;
            return redisUtil.hasKey(tokenKey);
        } catch (Exception e) {
            return false;
        }
    }
} 